package com.hudak.config;

import java.util.Properties;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "customerEntityManager", transactionManagerRef = "customerTransactionManager", 
	basePackages = {"com.hudak" })
public class PrimaryDBConfig {
	@Autowired
	private DataSourceConfig dsConfig;
	
	
	@Bean(name = "customerEntityManager")
	public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
		JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
		LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
		em.setDataSource(dataSource());
		em.setPackagesToScan(new String[] {"com.hudak"});
		em.setJpaVendorAdapter(vendorAdapter);
		em.setJpaProperties(jpaProperties());
		em.setPersistenceUnitName("customers");

		return em;
	}
	
	Properties jpaProperties(){
		Properties properties = new Properties();
		properties.setProperty("hibernate.hbm2ddl.auto", "update");
		properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
		properties.setProperty("hibernate.show_sql", "true");
		
		return properties;
	}
	
	@Bean
	public DataSource dataSource(){
		
		DruidDataSource dds= new DruidDataSource();
		dds.setDriverClassName(dsConfig.getDriverClassName());
		dds.setUrl(dsConfig.getUrl());
		dds.setUsername(dsConfig.getUsername());
		dds.setPassword(dsConfig.getPassword());
		return dds;
	}	
	
	@Bean(name = "customerTransactionManager")
	@Primary
	public JpaTransactionManager transactionManager(EntityManagerFactory customerEntityManager){
		JpaTransactionManager transactionManager = new JpaTransactionManager();
		transactionManager.setEntityManagerFactory(customerEntityManager);
		
		return transactionManager;
	}

}
